package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    //RPC远程调用技术
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;
    
    /**
     * 体检预约处理
     * @param map
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //取出Redis数据库中短信验证码
        String telephone = (String) map.get("telephone");
        System.out.println("telephone =111111111111111111111111 " + telephone);
        String validateCodeRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //获取表单提交的验证码
        String validateCode = (String) map.get("validateCode");
        System.out.println("validateCode =222222222222222222 " + validateCode);
        System.out.println("3333333333333333333333333");
        //将输入的验证码与redis数据库中做对比
        if(validateCodeRedis != null && validateCode != null && validateCodeRedis.equals(validateCode)) {
            Result result = null;
            System.out.println("4444444444444444444444444444");
            //设置预约类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            try {
                //调用业务层处理数据
                result = orderService.order(map);

            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.FWQ_FAIL);
            }
            if (result != null && result.isFlag()) {

                //预约成功，可以为用户发送短信
                try{
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone, (String) map.get("orderDate"));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("result =+++++++++++++++++++ " + result);
            return result;

        }else{
            //如果比对不成功，返回结果给页面 ，提示 对应 的 错误信息,验证码比对不成功提示验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
